from flask_restful import abort
from sqlalchemy.exc import IntegrityError
import pdfkit
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.lib.units import cm
from reportlab.pdfgen import canvas
from redash import models, limiter
import json
from redash.permissions import (
    require_admin_default,
)
from redash.handlers.base import (
    BaseResource,
    require_fields,
)
import os
import datetime
import uuid
from flask import Flask, flash, request, redirect, url_for, send_from_directory
from werkzeug.utils import secure_filename
from redash import settings
import subprocess
from subprocess import Popen, PIPE
# import sys
# import argparse
# from pywpsrpc.rpcwpsapi import (createWpsRpcInstance, wpsapi)
# from pywpsrpc.common import (S_OK, QtApp)

# formats = {
#     "doc": wpsapi.wdFormatDocument,
#     "docx": wpsapi.wdFormatXMLDocument,
#     "rtf": wpsapi.wdFormatRTF,
#     "html": wpsapi.wdFormatHTML,
#     "pdf": wpsapi.wdFormatPDF,
#     "xml": wpsapi.wdFormatXML,
# }
class Uploadfile(BaseResource):
    def post(self,sourcetype,types,bytstatus,nature,sourceid):
        f = request.files['file']
        # // 截取文件类型;这里可以根据文件类型进行判断
        filetype=settings.FILEUPLOAD["filetype"]
        type = f.filename[(f.filename.rindex('.') + 1):];
        type = type.lower()
        if not (type in filetype):
            return {"code": "error", "msg": "该文件类型不支持上传"}
        # if not ('.' in f.filename and  f.filename.rsplit('.', 1)[1].lower() in {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif','doc','docx'}):
        #     return {"code": "error", "msg": "该文件类型不支持上传"}
        size = len(f.read())
        maxsize = settings.FILEUPLOAD["maxsize"]
        if (size> maxsize * 1024 * 1024):
            return {"code": "error", "msg": "该文件" +{size/(1024*1024)}+"M,超过200M，不能上传"}
        # 当前文件所在路径
        path =settings.FILEUPLOAD["path"]
        date = datetime.datetime.now()
        ymdstr =  date.strftime("%Y%m%d")
        basepath = os.path.join(path, ymdstr)
        if not os.path.exists(basepath):
            os.makedirs(basepath)
        # // 重构文件名
        uid = str(uuid.uuid1())
        uid = uid.replace("-","")
        filename = uid + "." + type
        #filename = (str(uuid.uuid1())).replace("-","") + "." + type

        if os.path.isfile(os.path.join(basepath,filename)):
            return {"code": "error", "msg": "该文件已存在，不能上传","filename":"","url":""}
        # 一定要先创建该文件夹，不然会提示没有该路径
        upload_path = os.path.join(basepath, filename)
        # // 创建文件实例
        # mff = open(upload_path, 'ab')
        # mff.write(f.read())
        # mff.close()
        # 保存文件
        f.seek(0)
        f.save(upload_path)
        filename = os.path.join('static/file/',ymdstr, filename)
        try:
            attaches = models.Attaches.get_by_id(sourceid,sourcetype)
            ps = attaches.to_dict()
            annex = ps['annex']
            annex.append({'uid': ''+uid+'', 'name': ''+f.filename+'','type': ''+types+'','nature':int(nature), 'status': 'done','bytstatus':int(bytstatus),'url':''+filename+''})
            params = dict(annex=json.loads(json.dumps(annex)))
            self.update_model(attaches, params)
            models.db.session.commit()
        except :
            attaches = models.Attaches(
            userid=self.current_user.id,
            org=self.current_org,
            type = sourcetype,
            annex =[{"uid": ""+uid+"", "name": ""+f.filename+"","type": ""+types+"","nature":int(nature), "status": "done","bytstatus":int(bytstatus),"url":""+filename+""}],
            status =0,
            sourcetype =sourcetype,
            sourceid =sourceid,
            )
            try:
                models.db.session.add(attaches)
                models.db.session.commit()
            except :
                abort(400, message="附件上传失败.") 

        return {"code": "sucess","msg":"上传成功！","filename":filename,"url":""}


class Uploadcontracttextfile(BaseResource):
    def post(self, contract_id):
        f = request.files['file']        
        # // 截取文件类型;这里可以根据文件类型进行判断
        filetype=settings.FILEUPLOAD["filetype"]
        type = f.filename[(f.filename.rindex('.') + 1):];
        type = type.lower()
        if not (type in 'doc,docx,pdf'):
            return {"code": "error", "msg": "该文件类型不支持上传"}
        
        size = len(f.read())
        maxsize = settings.FILEUPLOAD["maxsize"]
        if (size> maxsize * 1024 * 1024):
            return {"code": "error", "msg": "该文件" +{size/(1024*1024)}+"M,超过200M，不能上传"}
        # 当前文件所在路径
        path =settings.FILEUPLOAD["path"]
        date = datetime.datetime.now()
        ymdstr =  date.strftime("%Y%m%d")
        try:
            result = models.Contracts.get_by_id(contract_id)
            strdate=result.templatecontent.split('/')
            strhz=strdate[-1].split('.')
            if strhz[-1]=='doc' or strhz[-1]=='docx' :
                ymdstr =strdate[len(strdate)-2]
        except :
            pass
        basepath = os.path.join(path, ymdstr)
        if not os.path.exists(basepath):
            os.makedirs(basepath)

        filename = f.filename
        # 一定要先创建该文件夹，不然会提示没有该路径
        upload_path = os.path.join(basepath, filename)
        # // 创建文件实例
        # mff = open(upload_path, 'ab')
        # mff.write(f.read())
        # mff.close()
        # 保存文件
        f.seek(0)
        f.save(upload_path)
        if (type in 'pdf'):
            filename = os.path.join(ymdstr, filename)
            return {"code": "sucess","msg":"上传成功！","filename":filename,"url":""}
        #转PDF
        timeout=None
        args = ['libreoffice', '--headless', '--convert-to', 'pdf', '--outdir',basepath, upload_path]
        process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
        #convert_to(upload_path, "pdf")
        #os.system("libreoffice --convert-to pdf:writer_pdf_Export %s --outdir %s" % (upload_path, basepath))
     
        #======================end=====================
        file = filename.split('.')[0]#不带后缀的文件名
#         pdf_file_in =os.path.join(basepath, file+'.pdf')
#         pdf_file_out =os.path.join(basepath, file+'out.pdf')
#    # def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):
#         pdf_output = PdfFileWriter()
#         pdf_input = PdfFileReader(open(pdf_file_in, 'rb'))
#         #RectangleObject([0, 0, 612, 792])
#         # PDF文件被加密了
#         if pdf_input.getIsEncrypted():
#             print('该PDF文件被加密了.')
#             # 尝试用空密码解密
#             try:
#                 pdf_input.decrypt('')
#             except Exception as e:
#                 print('尝试用空密码解密失败.')
#                 return False
#             else:
#                 print('用空密码解密成功.')
#         pageNum = pdf_input.getNumPages()
#         # 给每一页打水印
#         for i in range(pageNum):
#             page = pdf_input.getPage(i)
#             page.compressContentStreams()  # 压缩内容
#             pdf_output.addPage(page)
#             print("第{}页".format(i))
    
#         with open(pdf_file_out, 'wb') as out:
#             pdf_output.write(out)
        # 返回上传成功界面
        filename = os.path.join(ymdstr, filename)
        return {"code": "sucess","msg":"上传成功！","filename":filename,"url":""}

class Downloadfile(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        filename = req["filename"]
        filename = filename.replace("static/file/","")
        # 当前文件所在路径
        basepath = settings.FILEUPLOAD["path"]
        if not os.path.exists(basepath):
            os.makedirs(basepath)

        type = filename[(filename.rindex('.') + 1):];
        type = type.lower()
        
        if not os.path.isfile(os.path.join(basepath,filename)):
            if (type in 'doc,docx'):
                filename = filename[(filename.rindex('.') - 1):] +".pdf";
        if not os.path.isfile(os.path.join(basepath,filename)):
            return {"code": "error", "msg": "该文件不存在，不能下载"}
        # 一定要先创建该文件夹，不然会提示没有该路径
        upload_path = os.path.join(basepath, filename)
        # 下载文件
        # return send_from_directory(upload_path, filename, as_attachment=True)
        # if os.path.isfile(os.path.join(basepath, filename)):as_attachment=True
        return send_from_directory(basepath, filename,as_attachment=True)
         # raise exceptions.MyHttpNotFound('not found file')
        # 返回上传成功界面
        # return {"code": "sucess","msg":"上传成功！"}
class Removefile(BaseResource):
    def post(self,sourcetype,sourceid,uid):
        req = request.get_json(force=True)
        try:
            attaches = models.Attaches.get_by_id(sourceid,sourcetype)
            ps = attaches.to_dict()
            annex = json.loads(json.dumps(ps['annex'])) 
            for i in range(len(annex)):
                if annex[i]["uid"] == uid:
                    annex.pop(i)
                    break
            params = dict(annex=annex)
            self.update_model(attaches, params)
            models.db.session.commit()
        except :
            abort(400, message="删除失败.") 
        # 当前文件所在路径20210505改为不删除
        # basepath = os.path.join(settings.FILEUPLOAD["path"], filename)
        # if (os.path.exists(basepath)):
        #     os.remove(basepath)
        # else:
        #     return {"code": "error","msg":"文件不存在，删除失败！"}
        return {"code": "sucess","msg":"删除成功！"}

class Htmltopdf(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        filename = req["filename"]
        filetype = req["filetype"] #0--url,1--html,2--string
        file =  req["file"]
        #filepth = os.getcwd()
        pdfmetrics.registerFont(TTFont('song', os.getcwd()+'/fonts/simsun.ttc'))  # 宋体
       # path = os.getcwd() #获取当前工作目录路径
        path =settings.FILEUPLOAD["path"]
        #图片路径
        pngpath = os.path.join(path, 'waterseal.png')
        #图片路径
        # pngpath2 = os.path.join(path, 'gold.png')

        basepath = os.path.join(path, 'prints')
        if not os.path.exists(basepath):
            os.makedirs(basepath)
       # path = os.path.abspath('.') #获取当前工作目录路径
       # path =  os.path.abspath('test.txt') #获取当前目录文件下的工作目录路径
       # path =  os.path.abspath('..') #获取当前工作的父目录 ！注意是父目录路径
       # path =  os.path.abspath(os.curdir) #获取当前工作目录路径 
       # pdfkit.from_file(file,os.path.join(basepath, filename+'temp.pdf'))
        body = """<html>
            <head>
                <meta charset="UTF-8">
                    <style>
                        body {
                            margin: 0 auto;
                            width: 1000px;
                            height: 1200px;
                        }
             
                        div {
                            width: 1000px;
                            height: 1200px;
                        }
                        table, tr, td, th, tbody, thead, tfoot {page-break-inside: avoid !important;}
                    </style>
            </head>
            """ +file +"""
            </html>"""
        pdfkit.from_string(body,os.path.join(basepath, filename+'temp.pdf'))
       # pdfkit.from_url('http://localhost:5000/public/dashboards/qb9XyFAB8mgt40fSP37HQjPn9iPJwzrzbu78mdqv',os.path.join(basepath, filename+'temp.pdf'))
       # pdfkit.from_url('http://baidu.com',os.path.join(basepath, filename+'temp.pdf'))
        f_pdf = os.path.join(basepath, 'mark.pdf') 
    #     content="成都市第六人民医院"
    #     #===============wenzi============================
    #     # 默认大小为21cm*29.7cm
    #     c = canvas.Canvas(f_pdf, pagesize=(21 * cm, 30 * cm))
    #     # 移动坐标原点(坐标系左下为(0,0))
    #     c.translate(1 * cm, 5 * cm)
    
    #     # 设置字体Helvetica
    #     c.setFont("song", 50)
    #     # 指定描边的颜色
    #     c.setStrokeColorRGB(0, 1, 0)
    #     # 指定填充颜色
    #     c.setFillColorRGB(0, 1, 0)
    #     # 画一个矩形
    #    # c.rect(cm, cm, 7 * cm, 17 * cm, fill=1)
    #     # 旋转45度，坐标系被旋转
    #     c.rotate(45)
    #     # 指定填充颜色
    #     c.setFillColorRGB(0.6, 0, 0)
    #     # 设置透明度，1为不透明
    #     c.setFillAlpha(0.3)
    #     # 画几个文本，注意坐标系旋转的影响
    #     c.drawString(3 * cm, 0 * cm, content)
    #     c.setFillAlpha(0.3)
    
    #     # 关闭并保存pdf文件
    #     c.save()
        #===========================================
        #=============图片水印=======================   
    
        c = canvas.Canvas(f_pdf, pagesize=(21 * cm, 30 * cm))
        c.setFillAlpha(0.1)  # 设置透明度
        # 这里的单位是物理尺寸
        print(c.drawImage(pngpath, 10.5 * cm, 5.3 * cm, 7 * cm, 1 * cm))
        # 这里的单位是物理尺寸
        # print(c.drawImage(pngpath2, 16 * cm, 5.3 * cm, 1 * cm, 1 * cm))
        c.save()
        #======================end=====================
       # create_watermark("dddddddd")

       # add_watermark("/home/yhy/contract/client/dist/file/outbaidu.pdf", f_pdf, "c111.pdf")
        pdf_file_in =os.path.join(basepath, filename+'temp.pdf')
        pdf_file_mark =f_pdf
        pdf_file_out =os.path.join(basepath, filename+'.pdf')
   # def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):
        pdf_output = PdfFileWriter()
        pdf_input = PdfFileReader(open(pdf_file_in, 'rb'))
        #RectangleObject([0, 0, 612, 792])
        # PDF文件被加密了
        if pdf_input.getIsEncrypted():
            print('该PDF文件被加密了.')
            # 尝试用空密码解密
            try:
                pdf_input.decrypt('')
            except Exception as e:
                print('尝试用空密码解密失败.')
                return False
            else:
                print('用空密码解密成功.')
    
        # 获取PDF文件的页数
        pageNum = pdf_input.getNumPages()
        # 读入水印pdf文件
        pdf_watermark = PdfFileReader(open(pdf_file_mark, 'rb'))
        # 给每一页打水印
        for i in range(pageNum):
            page = pdf_input.getPage(i)
            page.mergePage(pdf_watermark.getPage(0))
            page.compressContentStreams()  # 压缩内容
            pdf_output.addPage(page)
            print("第{}页".format(i))

        # pdf_output.encrypt(user_pwd="",owner_pwd="123456")
        with open(pdf_file_out, 'wb') as out:
            pdf_output.write(out)
       #=======================================================
        # 当前文件所在路径
        return send_from_directory(basepath, filename+'.pdf',as_attachment=True)


    # 创建文字pdf
    def create_watermark(content):
        # 默认大小为21cm*29.7cm
        c = canvas.Canvas("/home/yhy/contract/client/dist/file/mark.pdf", pagesize=(30 * cm, 30 * cm))
        # 移动坐标原点(坐标系左下为(0,0))
        c.translate(10 * cm, 5 * cm)
    
        # 设置字体
        c.setFont("Helvetica", 80)
        # 指定描边的颜色
        c.setStrokeColorRGB(0, 1, 0)
        # 指定填充颜色
        c.setFillColorRGB(0, 1, 0)
        # 画一个矩形
        c.rect(cm, cm, 7 * cm, 17 * cm, fill=1)
        # 旋转45度，坐标系被旋转
        c.rotate(45)
        # 指定填充颜色
        c.setFillColorRGB(0.6, 0, 0)
        # 设置透明度，1为不透明
        c.setFillAlpha(0.3)
        # 画几个文本，注意坐标系旋转的影响
        c.drawString(3 * cm, 0 * cm, content)
        c.setFillAlpha(0.6)
        c.drawString(6 * cm, 3 * cm, content)
        c.setFillAlpha(1)
        c.drawString(9 * cm, 6 * cm, content)
    
        # 关闭并保存pdf文件
        c.save()

    # 制作图片水印pdf
    def create_watermark(f_jpg, f_pdf):
        w_pdf = 20 * cm
        h_pdf = 25 * cm
    
        c = canvas.Canvas(f_pdf, pagesize=(w_pdf, h_pdf))
        c.setFillAlpha(0.5)  # 设置透明度
        # 这里的单位是物理尺寸
        print(c.drawImage(f_jpg, 12 * cm, 17 * cm, 6 * cm, 6 * cm))
        c.save()
    
    
    # 所有路径为绝对路径
    def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):
        pdf_output = PdfFileWriter()
        pdf_input = PdfFileReader(open(pdf_file_in, 'rb'))
        # PDF文件被加密了
        if pdf_input.getIsEncrypted():
            print('该PDF文件被加密了.')
            # 尝试用空密码解密
            try:
                pdf_input.decrypt('')
            except Exception as e:
                print('尝试用空密码解密失败.')
                return False
            else:
                print('用空密码解密成功.')
    
        # 获取PDF文件的页数
        pageNum = pdf_input.getNumPages()
        # 读入水印pdf文件
        pdf_watermark = PdfFileReader(open(pdf_file_mark, 'rb'))
        # 给每一页打水印
        for i in range(pageNum):
            page = pdf_input.getPage(i)
            page.mergePage(pdf_watermark.getPage(0))
            page.compressContentStreams()  # 压缩内容
            pdf_output.addPage(page)
            print("第{}页".format(i))
    
        with open(pdf_file_out, 'wb') as out:
            pdf_output.write(out)

class Wordtopdf(BaseResource):
    def post(self):
        req = request.get_json(force=True)
        filename = req["filename"]
        filetype = req["filetype"] #0--url,1--html,2--string
        file =  req["file"]
        #filepth = os.getcwd()
        pdfmetrics.registerFont(TTFont('song', os.getcwd()+'/fonts/simsun.ttc'))  # 宋体
       # path = os.getcwd() #获取当前工作目录路径
        path =settings.FILEUPLOAD["path"]
        #图片路径
        pngpath = os.path.join(path, 'tyyy.png')
        #图片路径
        # pngpath2 = os.path.join(path, 'gold.png')

        basepath = os.path.join(path, 'prints')
        if not os.path.exists(basepath):
            os.makedirs(basepath)

        """将word 转换为pdf

        函数说明:将路径为infile的word文件转换为pdf,保存进路径为outfile的pdf文件.

        参数: outfile(str):保存文件pdf 的路径.

        参数: infile(str):word文件的路径.

        参数: timeout:转换文件时的时间延迟.
        """
        timeout=None
        file=file.replace('static/file/','')
        file=os.path.join(path, file)
        # args = ['libreoffice', '--headless', '--convert-to', 'pdf', '--outdir',basepath, file]
        # process = subprocess.run(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=timeout)
        #re.search('-> (.*?) using filter', process.stdout.decode())

        #pdfkit.from_string(body,os.path.join(basepath, filename+'temp.pdf'))
        f_pdf = os.path.join(basepath, 'mark.pdf') 
   
        #=============图片水印=======================   
    
        c = canvas.Canvas(f_pdf, pagesize=(21 * cm, 30 * cm))
        c.setFillAlpha(0.2)  # 设置透明度
        # 这里的单位是物理尺寸
        #print(c.drawImage(pngpath, 16 * cm, 5.3 * cm, 7 * cm, 2 * cm))
        print(c.drawImage(pngpath, 4 * cm, 4 * cm, 14* cm, 6 * cm))
        # 这里的单位是物理尺寸
        # print(c.drawImage(pngpath2, 16 * cm, 5.3 * cm, 1 * cm, 1 * cm))
        c.save()
        #======================end=====================
        pdf_file_in = file.replace('.docx','.pdf').replace('.doc','.pdf')
        # file = os.path.basename(file)#带后缀的文件名
        # file = file.split('.')[0]#不带后缀的文件名
        # pdf_file_in =os.path.join(basepath, file+'.pdf')
        pdf_file_mark =f_pdf
        pdf_file_out =os.path.join(basepath, filename+'.pdf')
   # def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):
        pdf_output = PdfFileWriter()
        pdf_input = PdfFileReader(open(pdf_file_in, 'rb'))
        #RectangleObject([0, 0, 612, 792])
        # PDF文件被加密了
        if pdf_input.getIsEncrypted():
            print('该PDF文件被加密了.')
            # 尝试用空密码解密
            try:
                pdf_input.decrypt('')
            except Exception as e:
                print('尝试用空密码解密失败.')
                return False
            else:
                print('用空密码解密成功.')
    
        # 获取PDF文件的页数
        pageNum = pdf_input.getNumPages()
        # 读入水印pdf文件
        pdf_watermark = PdfFileReader(open(pdf_file_mark, 'rb'))
        # 给每一页打水印
        for i in range(pageNum):
            page = pdf_input.getPage(i)
            page.mergePage(pdf_watermark.getPage(0))
            page.compressContentStreams()  # 压缩内容
            pdf_output.addPage(page)
            print("第{}页".format(i))

        # pdf_output.encrypt(user_pwd="",owner_pwd="123456")
        with open(pdf_file_out, 'wb') as out:
            pdf_output.write(out)
       #=======================================================
        # 当前文件所在路径
        return send_from_directory(basepath, filename+'.pdf',as_attachment=True)


    # 创建文字pdf
    def create_watermark(content):
        # 默认大小为21cm*29.7cm
        c = canvas.Canvas("/home/yhy/contract/client/dist/file/mark.pdf", pagesize=(30 * cm, 30 * cm))
        # 移动坐标原点(坐标系左下为(0,0))
        c.translate(10 * cm, 5 * cm)
    
        # 设置字体
        c.setFont("Helvetica", 80)
        # 指定描边的颜色
        c.setStrokeColorRGB(0, 1, 0)
        # 指定填充颜色
        c.setFillColorRGB(0, 1, 0)
        # 画一个矩形
        c.rect(cm, cm, 7 * cm, 17 * cm, fill=1)
        # 旋转45度，坐标系被旋转
        c.rotate(45)
        # 指定填充颜色
        c.setFillColorRGB(0.6, 0, 0)
        # 设置透明度，1为不透明
        c.setFillAlpha(0.3)
        # 画几个文本，注意坐标系旋转的影响
        c.drawString(3 * cm, 0 * cm, content)
        c.setFillAlpha(0.6)
        c.drawString(6 * cm, 3 * cm, content)
        c.setFillAlpha(1)
        c.drawString(9 * cm, 6 * cm, content)
    
        # 关闭并保存pdf文件
        c.save()

    # 制作图片水印pdf
    def create_watermark(f_jpg, f_pdf):
        w_pdf = 20 * cm
        h_pdf = 25 * cm
    
        c = canvas.Canvas(f_pdf, pagesize=(w_pdf, h_pdf))
        c.setFillAlpha(0.5)  # 设置透明度
        # 这里的单位是物理尺寸
        print(c.drawImage(f_jpg, 12 * cm, 17 * cm, 6 * cm, 6 * cm))
        c.save()
    
    
    # 所有路径为绝对路径
    def add_watermark(pdf_file_in, pdf_file_mark, pdf_file_out):
        pdf_output = PdfFileWriter()
        pdf_input = PdfFileReader(open(pdf_file_in, 'rb'))
        # PDF文件被加密了
        if pdf_input.getIsEncrypted():
            print('该PDF文件被加密了.')
            # 尝试用空密码解密
            try:
                pdf_input.decrypt('')
            except Exception as e:
                print('尝试用空密码解密失败.')
                return False
            else:
                print('用空密码解密成功.')
    
        # 获取PDF文件的页数
        pageNum = pdf_input.getNumPages()
        # 读入水印pdf文件
        pdf_watermark = PdfFileReader(open(pdf_file_mark, 'rb'))
        # 给每一页打水印
        for i in range(pageNum):
            page = pdf_input.getPage(i)
            page.mergePage(pdf_watermark.getPage(0))
            page.compressContentStreams()  # 压缩内容
            pdf_output.addPage(page)
            print("第{}页".format(i))
    
        with open(pdf_file_out, 'wb') as out:
            pdf_output.write(out)

# class ConvertException(Exception):
    
#     def __init__(self, text, hr):
#         self.text = text
#         self.hr = hr

#     def __str__(self):
#         return """Convert failed:Details: {}ErrCode: {}""".format(self.text, hex(self.hr & 0xFFFFFFFF))

# def convert_to(paths, format, abort_on_fails=False):
#     hr, rpc = createWpsRpcInstance()
#     if hr != S_OK:
#         raise ConvertException("Can't create the rpc instance", hr)

#     hr, app = rpc.getWpsApplication()
#     if hr != S_OK:
#         raise ConvertException("Can't get the application", hr)

#     # we don't need the gui
#     app.Visible = False

#     docs = app.Documents

#     hr, doc = docs.Open(paths, ReadOnly=True)
#     if hr != S_OK:
#         return hr

#     out_dir = os.path.dirname(os.path.realpath(paths)) 
#     os.makedirs(out_dir, exist_ok=True)

#     # you have to handle if the new_file already exists
#     new_file = out_dir + "/" + os.path.splitext(os.path.basename(paths))[0] + "." + format
#     ret = doc.SaveAs2(new_file, FileFormat=formats[format])

#     # always close the doc
#     doc.Close(wpsapi.wdDoNotSaveChanges)

#     return ret

#     def _handle_result(hr):
#         if abort_on_fails and hr != S_OK:
#             raise ConvertException("convert_file failed", hr)

#     for path in paths:
#         abs_path = os.path.realpath(path)
#         if os.path.isdir(abs_path):
#             files = [(os.path.join(abs_path, f)) for f in os.listdir(abs_path)]
#             for file in files:
#                 hr = convert_file(file, docs, format)
#                 _handle_result(hr)
#         else:
#             hr = convert_file(abs_path, docs, format)
#             _handle_result(hr)

#     app.Quit()


# def convert_file(file, docs, format):
#     hr, doc = docs.Open(file, ReadOnly=True)
#     if hr != S_OK:
#         return hr

#     out_dir = os.path.dirname(os.path.realpath(file)) + "/out"
#     os.makedirs(out_dir, exist_ok=True)

#     # you have to handle if the new_file already exists
#     new_file = out_dir + "/" + os.path.splitext(os.path.basename(file))[0] + "." + format
#     ret = doc.SaveAs2(new_file, FileFormat=formats[format])

#     # always close the doc
#     doc.Close(wpsapi.wdDoNotSaveChanges)

#     return ret


# # def main():
# #     parser = argparse.ArgumentParser()
# #     parser.add_argument("--format", "-f",
# #                         required=True,
# #                         metavar="<DOC_TYPE>",
# #                         choices=["doc", "docx", "rtf", "html", "pdf", "xml"],
# #                         help="convert to <DOC_TYPE>,")

# #     parser.add_argument("--abort", "-a",
# #                         action="store_true",
# #                         help="abort if one convert fails")

# #     parser.add_argument("path",
# #                         metavar="<path>",
# #                         nargs='+',
# #                         help="the <path> can be one or more file or folder")

# #     args = parser.parse_args()

# #     qApp = QtApp(sys.argv)

# #     try:
# #         convert_to(args.path, args.format, args.abort)
# #     except ConvertException as e:
# #         print(e)